package com.ilas.service.impl;

import com.ilas.config.DynamicDataSourceContextHolder;
import com.ilas.dao.BizUserDao;
import com.ilas.entity.BizUser;
import com.ilas.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>${Description}</p>
 *
 * @author luzck
 * @date 2021/3/29 15:09
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private BizUserDao userDao;

    @Override
    public List<BizUser> getList() {
        //  查询slave数据库的用户列表
        // 切换slave数据源
        DynamicDataSourceContextHolder.setDataSourceKey("slave");
        log.info("getDataSourceKey-->{}", DynamicDataSourceContextHolder.getDataSourceKey());
        List<BizUser> bizUsers = userDao.queryAll(null);
        System.out.println("-------- LZC -------- bizUsers值=" + bizUsers.toString() + " , " + "当前类=UserServiceImpl.getList()");
        DynamicDataSourceContextHolder.clearDataSourceKey();

        //  查询master数据库的用户列表
        // 切换master数据源
        DynamicDataSourceContextHolder.setDataSourceKey("master");
        log.info("getDataSourceKey-->{}", DynamicDataSourceContextHolder.getDataSourceKey());
        List<BizUser> bizUsers2 = userDao.queryAll(null);
        System.out.println("-------- LZC -------- bizUsers值=" + bizUsers2.toString() + " , " + "当前类=UserServiceImpl.getList()");

        // 合并结果集
        bizUsers2.addAll(bizUsers);
        return bizUsers2;
    }

    @Override
    public List<BizUser> getList2() {
        return  userDao.queryAll(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(BizUser user) {
        int insert = userDao.insert(user);

        // 测试事务是否起效
        //int reuslt = 1/0;
        //System.out.println("-------- LZC -------- 值=" + reuslt +" , " + "当前类=UserServiceImpl.insertUser()");

        return insert > 0;
    }

}
